<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模板类型"
                    prop="templatetype"
      >
        <el-select v-model="queryParams.templatetype"
                   placeholder="请选择"
                   class="filter-item"
                   style="width: 220px"
                   @change="handleQuery"
        >
          <el-option
            v-for="dict in operation_template_list"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="完成时间"
        prop="specificdate"
      >
        <el-date-picker
          @change="getList"
          v-model="queryParams.specificdate"
          type="date"
          :disabled-date="disabledDate"
          value-format="YYYY-MM-DD"
          placeholder="请选择用于生成单独一日的任务，如果特定日期要可选，周期必须选M">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
        <el-button
          type="primary"
          plain
          icon="Upload"
          @click="generateResult"
          v-hasPermi="['operation:operationdailyResult:generate']"
        >生成</el-button>
        <el-button
          v-if="queryParams.specificdate===parseTime(new Date(),'{y}-{m}-{d}')"
          type="success"
          plain
          icon="Plus"
          :disabled="multiple"
          @click="handleFinishWork"
          v-hasPermi="['operation:operationdaily:export']"
        >完成</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button icon="download" type="danger" @click="handleExport(operation_template_list,queryParams.specificdate)">导出</el-button>
      </el-form-item>
    </el-form>

<!--    <el-row :gutter="10" class="mb8">-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="Upload"-->
<!--          @click="generateResult"-->
<!--          v-hasPermi="['operation:operationdailyResult:generate']"-->
<!--        >生成</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          v-if="queryParams.specificdate===parseTime(new Date(),'{y}-{m}-{d}')"-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="Plus"-->
<!--          :disabled="multiple"-->
<!--          @click="handleFinishWork"-->
<!--          v-hasPermi="['operation:operationdaily:export']"-->
<!--        >完成</el-button>-->
<!--      </el-col>-->
<!--      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
<!--    </el-row>-->
    <div style="display: flex;float: right" >
      日期：{{queryParams.specificdate}}
    </div>
    <el-table v-loading="loading"
              :data="operationdailyList"
              highlight-current-row
              width="100%"
              :span-method="arraySpanMethod(operationdailyList)"
              @selection-change="handleSelectionChange">
      <el-table-column :label="title" align="center">
        <template #header>
          <dict-tag :options="operation_template_list" :value="queryParams.templatetype"/>
        </template>
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column type="index" width="50"/>
        <el-table-column label="清算流程分段" align="center" width="150">
          <el-table-column label="工作内容" prop="summary" width="200"/>
          <el-table-column label="时间" prop="operatetime" width="120"/>
        </el-table-column>
        <el-table-column label="清算工作状态" align="center" prop="result" width="80">
          <template #default="scope">
            <el-icon v-if="scope.row.result==='S'" style="font-size: 40px"><Check/></el-icon>
            <el-icon v-else-if="scope.row.result==='F'" style="font-size: 40px"><Close/></el-icon>
            <el-icon v-else></el-icon>
          </template>
        </el-table-column>
        <el-table-column label="清算工作具体内容" align="left" prop="content">
          <template #default="scope">
<!--            <pre>{{scope.row.content}}</pre>-->
            <span v-html="scope.row.content" style="white-space:pre-wrap"/>
          </template>
        </el-table-column>
        <el-table-column label="操作人" align="center" prop="updateBy" width="100"/>
        <el-table-column label="操作时间" align="center" prop="updateTime" width="180"/>
        <el-table-column label="备注" align="center" prop="memo" width="150">
          <template #default="scope">
            <span v-html="scope.row.memo" style="white-space:pre-wrap"/>
          </template>
        </el-table-column>
        <el-table-column label="操作员盖章" align="center" prop="result" width="250">
          <template #default="scope">
            <el-button
              type="primary"
              icon="link"
              :disabled="queryParams.specificdate!=parseTime(new Date(),'{y}-{m}-{d}')&&scope.row.result!=undefined"
              link
              @click="handleFiniWork(scope.row,'S')"
            >完成</el-button>
<!--              :disabled="scope.row.result==='S'"-->
            <el-button
              type="primary"
              icon="close"
              :disabled="queryParams.specificdate!=parseTime(new Date(),'{y}-{m}-{d}')&&scope.row.result!=undefined"
              link
              @click="handleFiniWork(scope.row,'F')"
            >失败</el-button>
            <el-button
            type="primary"
            icon="EditPen"
            :disabled="queryParams.specificdate!=parseTime(new Date(),'{y}-{m}-{d}')&&scope.row.result!=undefined"
            link
            @click="handleEdit(scope.row)"
            >备注</el-button>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>

    <!-- 添加或修改运营部门日志记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="operationdailyRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模板类型"
                      prop="templatetype"
        >
          <el-select v-model="queryParams.templatetype"
                     disabled
                     placeholder="请选择"
                     class="filter-item"
                     style="width: 220px"
                     @change="handleQuery"
          >
            <el-option
              v-for="dict in operation_template_list"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作内容"
                      prop="summary">
          <el-input
            v-model="form.summary"
            placeholder="请输入工作内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否启用" prop="flag">
          <el-select
            v-model="form.flag"
          >
            <el-option label="否" value="0"/>
            <el-option label="是" value="1"/>
          </el-select>
        </el-form-item>
        <el-form-item label="周期" prop="period">
          <el-input
            v-model="form.period"
            placeholder="D：每日；T：每工作日；C：每工作日并香港工作日；W1：每周第一个工作日；M30：每月最后一个工作日；S90：每季最后一个工作日；Y365：每年最后一个工作日"
          ></el-input>
        </el-form-item>
        <el-form-item label="特定日期" prop="specificdate">
          <el-date-picker
            v-model="form.specificdate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择特定日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="时间"
                      prop="operatetime">
          <el-input
            v-model="form.operatetime"
            placeholder="请输入时间"
          />
        </el-form-item>
        <el-form-item label="清算工作具体内容"
                      prop="content"
        >
          <el-input
            type="textarea"
            v-model="form.content"
            placeholder="清算工作具体内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="关联系统"
                      prop="busisystemList">
          <el-select
            v-model="form.busisystemList"
            placeholder="请选择关联系统"
            multiple
          >
            <el-option
              v-for="item in systemList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              @keyup.enter="handleQuery"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="sort" :precision="2" :step="0.1"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="提交" v-model="failOpen">
      <el-form ref="operationdailyResultRef">
        <el-form-item label="备注" prop="memo">
<!--          <el-input-->
<!--            v-model="memo"-->
<!--            placeholder="请输入备注"-->
<!--          ></el-input>-->
          <editor v-model="memo"
                  placeholder="请输入备注"
                  :min-height="196"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitMemo">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Operationdaily">
import { listOperationdaily, getOperationdaily, delOperationdaily, addOperationdaily, updateOperationdaily } from "@/api/operation/operationdaily";
import {
  listOperationdailyResult,
  generateOperationdailyResult,
  finishWork,
  failWork
} from "@/api/operation/operationdailyResult";
import {parseTime} from "@/utils/ruoyi";
import {getSysList} from "@/api/operation/sqltool";
import {getCurrentInstance} from "vue";
import DictTag from "@/components/DictTag/index.vue";

const { proxy } = getCurrentInstance();
const {operation_template_list}= proxy.useDict("operation_template_list");
const operationdailyList = ref([]);
const open = ref(false);
const failOpen = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const memo = ref("");
const systemList = ref([]);
const memoValue = ref({});
// const pickDate = parseTime(new Date(),"{y}-{m}-{d}");
const reason = ref("");
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    templatetype: '2',
    summary: undefined,
    operatetime: undefined,
    content: undefined,
    period: undefined,
    specificdate: parseTime(new Date(),"{y}-{m}-{d}"),
    sort: undefined,
    flag: undefined,
    busioperations: undefined,
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    templatetype: [
      { required: true, message: "TA模板：1；FC模板：2；FA模板：3；不能为空", trigger: "change" }
    ],
    summary: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    operatetime: [
      { required: true, message: "下拉框，从cmdb获取不能为空", trigger: "blur" }
    ],
    content: [
      { required: true, message: "QS:清算; WJ:文件; SJ:数据不能为空", trigger: "blur" }
    ],
    period: [
      { required: true, message: "D：每日；T：每工作日；C：每工作日并香港工作日；W1：每周第一个工作日；M30：每月最后一个工作日；S90：每季最后一个工作日；Y365：每年最后一个工作日。不能为空", trigger: "blur" }
    ],
    specificdate: [
      { required: false, message: "用于生成单独一日的任务，如果特定日期要可选，周期必须选M不能为空", trigger: "blur" }
    ],
    sort: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    flag: [
      { required: true, message: "0：不启用；1:启用；不能为空", trigger: "blur" }
    ],
    busioperations: [
      { required: false, message: "涉及业务系统id，用逗号分割不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules ,successForm} = toRefs(data);

/** 查询运营部门日志记录列表 */
function getList() {
  loading.value = true;
  listOperationdailyResult(queryParams.value).then(response => {
    operationdailyList.value = response;
    console.log(response,"====")
    console.log(operationdailyList.value,"operationdailyList")
    total.value = response.total;
    loading.value = false;
  });
}

function disabledDate(time){
  return time.getTime() > Date.now()
}
function arraySpanMethod(tableData){
  console.log("========",tableData)
  const mergingRows = (tableData) => { // 表格数据列合并预处理,生成一个与行数相同的数组记录每一行设置的合并数
    // 如果是第一条记录（索引为0），向数组中加入1，并设置索引位置；
    // 如果不是第一条记录，则判断它与前一条记录是否相等，如果相等，
    // 则向mergingRows中添入元素0，并将前一位元素+1，表示合并行数+1，
    // 以此往复，得到所有行的合并数，0即表示该行不显示。
    const mergingRows = []
    let mergingPos = 0
    for (let i = 0; i < tableData.length; i++) { // tabledata 表格数据源
      if (i === 0) {
        mergingRows.push(1)
        mergingPos = 0
      } else {
        if (tableData[i].operatetime === tableData[i - 1].operatetime&&tableData[i].summary === tableData[i - 1].summary) {
          // 哪些数据是要合并的 合并的条件是什么 此处合并条件为categoryName 相同则进行合并
          mergingRows[mergingPos] += 1
          mergingRows.push(0)
        } else {
          mergingRows.push(1)
          mergingPos = i
        }
      }
    }
    return mergingRows
  }
  const data = mergingRows(tableData)
  console.log(data,"变更之后的数据=======")
  return ({rowIndex, columnIndex }) => {
    if (columnIndex === 2||columnIndex===3) { // 第一列
      const _row = data[rowIndex]
      const _col = _row > 0 ? 1 : 0
      return {
        rowspan: _row,
        colspan: _col
      }
    }
  }
}
// 取消按钮
function cancel() {
  open.value = false;
  failOpen.value=false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    templatetype: null,
    summary: null,
    operatetime: null,
    content: null,
    period: null,
    specificdate: null,
    sort: null,
    flag: null,
    busioperations: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("operationdailyRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

function getBusiList(){
  getSysList().then(response => {
    systemList.value = response.rows;
    console.log(systemList,"====");
  });
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  if(queryParams.value.templatetype==='1'){
    title.value = "资金业务检查清单";
  }else{
    title.value='TA日志表'
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id || ids.value
  getOperationdaily(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改运营部门日志记录";
  });
}

function handleFiniWork(row,result){
  failOpen.value = !failOpen.value
  memoValue.value.id = row.id
  memo.value = row.memo
  memoValue.value.result = result
}

function handleEdit(row){
  failOpen.value = !failOpen.value
  memoValue.value.id = row.id
  memo.value = row.memo
  memoValue.value.result = '';
}
function submitMemo(){
  memoValue.value.memo = memo
  failWork(memoValue.value).then(res=>{
    console.log(res)
    proxy.$modal.msgSuccess(res.msg);
    failOpen.value = !failOpen.value
    memo.value=''
    getList()
  })
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["operationdailyRef"].validate(valid => {
    if (valid) {
      form.value.templatetype = queryParams.value.templatetype;
      buttonLoading.value = true;
      if (form.value.id != null) {
        form.value.busisystems = form.value.busisystemList.join(",");
        updateOperationdaily(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        form.value.busisystems = form.value.busisystemList.join(",");
        addOperationdaily(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}
function generateResult(){
  generateOperationdailyResult(queryParams.value).then(response => {
    proxy.$modal.msgSuccess("生成成功");
    open.value = false;
    getList();
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除运营部门日志记录编号为"' + _ids + '"的数据项？').then(function() {
    loading.value = true;
    return delOperationdaily(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

function handleFinishWork(row, flag){
  console.log(row,"row")
  const _ids = row.id||ids.value;
  proxy.$modal.confirm('是否确认完成所选内容').then(function() {
    loading.value = true;
    return finishWork(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("完成成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导出按钮操作 */
function handleExport(name,time) {
  proxy.download('operation/operationdailyResult/export', {
    ...queryParams.value
  }, `${name.filter(x=>x.value===queryParams.value.templatetype)[0].label}_${time}日检查结果.xlsx`)
}
getBusiList();
getList();
</script>
